<?php
namespace framework\dao;
use framework\dao\i_DAO;
use \PDO;
/**
 * 类必须重写接口中的所有方法
 */
class PDODAO implements i_DAO
{
    //成员属性
    private $host;//服务器名称
    private $dbname;//数据库名称
    private $port;//端口号
    private $charset;//编码
    private $user;//用户名
    private $pwd;//密码
    private $pdo;//连接对象
    private static $instance;//存储类的唯一的实例

    private function __construct($config)
    {
        $this->host = isset($config['host']) ? $config['host'] : "localhost";
        $this->dbname = isset($config['dbname']) ? $config['dbname'] : "hzw_blog";
        $this->port = isset($config['port']) ? $config['port'] : '3306';
        $this->charset = isset($config['charset']) ? $config['charset'] : 'utf8';
        $this->user = isset($config['user']) ? $config['user'] : 'root';
        $this->pwd = isset($config['pwd']) ? $config['pwd'] : 'root';
        $dsn = "mysql:host=$this->host;dbname=$this->dbname;port=$this->dbname;charset=$this->charset;";
        try {
            $this->pdo = new PDO($dsn, $this->user, $this->pwd);
        } catch (PDOException $e) {
            echo $e->getMessage();
            exit();
        }
    }

    //向类的外部返回创建的唯一实例
    public static function getSingleInstance($config)
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }
    //禁止克隆
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }


//此方法只用来执行特定的sql语句：此语句的查询结果有多行
    public function fetchAll($sql)
    {
        $pdo_statement = $this->pdo->query($sql);
        if ($pdo_statement == false) {
            echo "sql语句错误:" . $this->pdo->errorInfo()[2];
            die();
        }
        return $pdo_statement->fetchAll(PDO::FETCH_ASSOC);
    }

//此方法只用来执行特定的sql语句：此语句的查询结果只有一行
    public function fetchRow($sql)
    {
        $pdo_statement = $this->pdo->query($sql);
        if ($pdo_statement == false) {
            echo "sql语句错误:" . $this->pdo->errorInfo()[2];
            die();
        }
        return $pdo_statement->fetch(PDO::FETCH_ASSOC);
    }

//此方法只用来执行特定的sql语句：此语句的查询结果只有一个数据
    public function fetchOne($sql)
    {
        $pdo_statement = $this->pdo->query($sql);
        if ($pdo_statement == false) {
            echo "sql语句错误:" . $this->pdo->errorInfo()[2];
            die();
        }
        return $pdo_statement->fetchColumn();
    }

//对数据进行转义包裹
    public function quote($data)
    {
        return $this->pdo->quote($data);
    }

//用于执行insert、update、delete语句
    public function query($sql)
    {
        $result = $this->pdo->exec($sql);
        if ($result == false) {
            echo "sql语句错误:" . $this->pdo->errorInfo()[2];
            die();
        }
        if ($result > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function insertId()
    {
        return $this->pdo->lastInsertId();
    }
}